#!/bin/bash

# FlowPlan端到端测试脚本
# 测试覆盖率目标: >80%

set -e  # 遇到错误立即退出

echo "=========================================="
echo "FlowPlan 端到端测试开始"
echo "=========================================="

# 检查环境
echo "1. 检查测试环境..."
if ! command -v curl &> /dev/null; then
    echo "错误: curl 未安装"
    exit 1
fi

if ! command -v docker &> /dev/null; then
    echo "错误: docker 未安装"
    exit 1
fi

# 启动服务
echo "2. 启动FlowPlan服务..."
docker-compose up -d

# 等待服务启动
echo "3. 等待服务启动完成..."
for i in {1..30}; do
    if curl -f http://localhost:8080/api/actuator/health &> /dev/null; then
        echo "后端服务已启动"
        break
    fi
    echo "等待后端服务启动... ($i/30)"
    sleep 2
done

# 测试用例
BASE_URL="http://localhost:8080/api"
TEST_RESULTS=()

# 测试1: 健康检查
echo "4. 测试健康检查..."
if curl -f $BASE_URL/actuator/health > /dev/null 2>&1; then
    echo "✓ 健康检查通过"
    TEST_RESULTS+=("PASS")
else
    echo "✗ 健康检查失败"
    TEST_RESULTS+=("FAIL")
fi

# 测试2: 用户注册
echo "5. 测试用户注册..."
REGISTER_RESULT=$(curl -s -X POST \
    -H "Content-Type: application/json" \
    -d '{
        "username": "testuser",
        "password": "Test123456",
        "email": "test@flowplan.com",
        "phone": "13800138000",
        "realName": "测试用户"
    }' \
    $BASE_URL/auth/register)

if echo $REGISTER_RESULT | grep -q "success"; then
    echo "✓ 用户注册成功"
    TEST_RESULTS+=("PASS")
else
    echo "✗ 用户注册失败: $REGISTER_RESULT"
    TEST_RESULTS+=("FAIL")
fi

# 测试3: 用户登录
echo "6. 测试用户登录..."
LOGIN_RESULT=$(curl -s -X POST \
    -H "Content-Type: application/json" \
    -d '{
        "username": "testuser",
        "password": "Test123456"
    }' \
    $BASE_URL/auth/login)

if echo $LOGIN_RESULT | grep -q "token"; then
    echo "✓ 用户登录成功"
    TEST_RESULTS+=("PASS")
    # 提取Token
    TOKEN=$(echo $LOGIN_RESULT | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
else
    echo "✗ 用户登录失败: $LOGIN_RESULT"
    TEST_RESULTS+=("FAIL")
    TOKEN=""
fi

# 测试4: 创建项目
echo "7. 测试创建项目..."
if [ -n "$TOKEN" ]; then
    PROJECT_RESULT=$(curl -s -X POST \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $TOKEN" \
        -d '{
            "projectName": "测试项目",
            "description": "端到端测试项目",
            "priority": "MEDIUM"
        }' \
        $BASE_URL/projects)
    
    if echo $PROJECT_RESULT | grep -q "success"; then
        echo "✓ 项目创建成功"
        TEST_RESULTS+=("PASS")
        PROJECT_ID=$(echo $PROJECT_RESULT | grep -o '"id":[^,]*' | cut -d':' -f2)
    else
        echo "✗ 项目创建失败: $PROJECT_RESULT"
        TEST_RESULTS+=("FAIL")
        PROJECT_ID=""
    fi
else
    echo "✗ 跳过项目创建测试（需要登录）"
    TEST_RESULTS+=("SKIP")
fi

# 测试5: 创建待办任务
echo "8. 测试创建待办任务..."
if [ -n "$TOKEN" ] && [ -n "$PROJECT_ID" ]; then
    TODO_RESULT=$(curl -s -X POST \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $TOKEN" \
        -d '{
            "projectId": '$PROJECT_ID',
            "title": "测试待办任务",
            "description": "端到端测试任务",
            "priority": "HIGH",
            "todoType": "DEVELOP"
        }' \
        $BASE_URL/todos)
    
    if echo $TODO_RESULT | grep -q "success"; then
        echo "✓ 待办任务创建成功"
        TEST_RESULTS+=("PASS")
    else
        echo "✗ 待办任务创建失败: $TODO_RESULT"
        TEST_RESULTS+=("FAIL")
    fi
else
    echo "✗ 跳过待办任务测试（需要项目）"
    TEST_RESULTS+=("SKIP")
fi

# 测试6: AI服务健康检查
echo "9. 测试AI服务..."
if [ -n "$TOKEN" ]; then
    AI_RESULT=$(curl -s -X GET \
        -H "Authorization: Bearer $TOKEN" \
        $BASE_URL/ai/status)
    
    if echo $AI_RESULT | grep -q "success"; then
        echo "✓ AI服务正常"
        TEST_RESULTS+=("PASS")
    else
        echo "✗ AI服务异常: $AI_RESULT"
        TEST_RESULTS+=("FAIL")
    fi
else
    echo "✗ 跳过AI服务测试（需要登录）"
    TEST_RESULTS+=("SKIP")
fi

# 测试7: WebSocket连接测试
echo "10. 测试WebSocket连接..."
WS_TEST_RESULT=$(timeout 5 curl -s --http1.1 \
    -H "Connection: Upgrade" \
    -H "Upgrade: websocket" \
    -H "Sec-WebSocket-Version: 13" \
    -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
    http://localhost:8080/ws/collaboration)

if [ $? -eq 124 ]; then
    echo "✓ WebSocket端点可访问"
    TEST_RESULTS+=("PASS")
else
    echo "✗ WebSocket连接失败"
    TEST_RESULTS+=("FAIL")
fi

# 清理测试数据
echo "11. 清理测试数据..."
if [ -n "$TOKEN" ] && [ -n "$PROJECT_ID" ]; then
    curl -s -X DELETE \
        -H "Authorization: Bearer $TOKEN" \
        $BASE_URL/projects/$PROJECT_ID > /dev/null
    echo "✓ 测试数据清理完成"
fi

# 停止服务
echo "12. 停止测试服务..."
docker-compose down

# 计算测试结果
TOTAL_TESTS=${#TEST_RESULTS[@]}
PASSED_TESTS=$(printf '%s\n' "${TEST_RESULTS[@]}" | grep -c "PASS")
FAILED_TESTS=$(printf '%s\n' "${TEST_RESULTS[@]}" | grep -c "FAIL")
SKIPPED_TESTS=$(printf '%s\n' "${TEST_RESULTS[@]}" | grep -c "SKIP")

PASS_RATE=$((PASSED_TESTS * 100 / TOTAL_TESTS))

echo "=========================================="
echo "测试结果汇总:"
echo "总测试数: $TOTAL_TESTS"
echo "通过: $PASSED_TESTS"
echo "失败: $FAILED_TESTS" 
echo "跳过: $SKIPPED_TESTS"
echo "通过率: $PASS_RATE%"
echo "=========================================="

# 检查是否达到目标覆盖率
if [ $PASS_RATE -ge 80 ]; then
    echo "✓ 达到目标测试覆盖率 (80%)"
    echo "✓ 端到端测试通过"
    exit 0
else
    echo "✗ 未达到目标测试覆盖率 (80%)"
    echo "✗ 端到端测试失败"
    exit 1
fi